package com.fz.controller;

import com.fz.dao.StudentDao;
import com.fz.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;


/**
 * Created by webrx on 2017-09-12.
 */
@Controller
public class StudentController {
    @Autowired
    protected StudentDao dao;
    //显示数据
    @RequestMapping("/queryall")
    public String queryall(Model model){
        model.addAttribute("student",dao.queryall());
       return "show";
     }
     //数据分页
     @RequestMapping("/query")
     public String  query(Model model,HttpServletRequest req){
         String s=req.getParameter("p");
         //当前页
         int count=s==null?1:Integer.parseInt(s);
         //一共多少条数据
         int ooo=dao.pagecount();
         //一页有多少条数据
         int size =3;
         //一共用多少页
         int pagecount=ooo%size==0? ooo/size : ooo/size+1;
         //逻辑判断
         if(count<1) count=1;
         if(count>pagecount) count =pagecount;
         //从起始位置开始
         int start=count*size-size;
         model.addAttribute("student",dao.query(start,size));
         model.addAttribute("count",count);
         model.addAttribute("pagecount",pagecount);
         return "query";
    }
    //通过id删除数据
    @RequestMapping("/delete/{id}/{count}")
    public String delete(@PathVariable("id") int id,@PathVariable("count") int p){
         dao.deleteById(id);
         return "redirect:/query?p="+p;
    }
    //点击jsp中修改显示 修改表单
    @RequestMapping( "/up/{id}/{count}")
    public String up(Model model,@PathVariable("count") int p,@PathVariable("id") int id){
       model.addAttribute("student",dao.qu(id));
       model.addAttribute("p",p);
        return "update";
    }
    //通过id修改数据
    @RequestMapping(value = "/update/{id}/{p}",method = RequestMethod.POST)
    public String update(Student student,@PathVariable("id") int id, @PathVariable("p") int p){
        dao.update(student);
        return "redirect:/query?p="+p;
    }
    //点击jsp 中添加数据 跳转到添加数据的表单
    @RequestMapping("/ins/{count}")
    public String ins(Model model,@PathVariable("count") int p){
        model.addAttribute("p",p);
        return "ins";
    }
    //添加数据
    @RequestMapping(value = "/insert/{p}",method = RequestMethod.POST)
    public String insert(Student student,@PathVariable("p") int p){
        //判断分页满了 添加数据去下一页
        //一共多少调数据
        int a=dao.pagecount();
        int aa=a%3;
        if(aa==0){
            p++;
        }
        dao.insert(student);
        return "redirect:/query?p="+p;
    }
}
